﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.IO;
using System.Threading.Tasks;

namespace xycn.AuthMidware
{
    /// <summary>
    /// 权限中间件
    /// </summary>
    public static class AuthorizeMiddler
    {
        public static IApplicationBuilder UseXlAuthorize(this IApplicationBuilder app)
        {
            return app.UseMiddleware<BaseAuthMiddlewareExtensions>();
        }
    }
    public class BaseAuthMiddlewareExtensions
    {
        private readonly RequestDelegate _next;
        //public static List<string> filter = new List<string>() { ".js", ".css", ".html", ".png", ".jpg", ".bmp" };

        public BaseAuthMiddlewareExtensions(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 记录请求日志
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                //context.Request.EnableBuffering();

                //var url = context.Request.Host + context.Request.Path;
                //var requestReader = new StreamReader(context.Request.Body);
                //var result = context.Request.Headers.TryGetValue("Authorization", out StringValues authStr);
                //if (!result || string.IsNullOrEmpty(authStr.ToString()))
                //{
                //    throw new UnauthorizedAccessException("未授权，请传递Header头的Authorization参数。");
                //}

                //var endpoint = context.GetEndpoint();

                //var atts = context.GetType().GetCustomAttributes(typeof(IAllowAnonymous), true);
                //if (atts.Contains(""))
                //{

                //}


                //var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();

                //if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
                //{
                //    await _next(context);
                //    return;
                //}
                ////var success = true;
                ////var jwtArr = result.Split('.');
                ////var header = JsonConvert.DeserializeObject<Dictionary<string, string>>(Base64UrlEncoder.Decode(jwtArr[0]));
                ////var payLoad = JsonConvert.DeserializeObject<Dictionary<string, string>>(Base64UrlEncoder.Decode(jwtArr[1]));

                ////var hs256 = new HMACSHA256(Encoding.ASCII.GetBytes(setting.SecurityKey));
                //////首先验证签名是否正确（必须的） 
                ////success = success && string.Equals(jwtArr[2], Base64UrlEncoder.Encode(hs256.ComputeHash(Encoding.UTF8.GetBytes(string.Concat(jwtArr[0], ".", jwtArr[1])))));
                ////if (!success)
                ////{
                ////    ResponseError(context, "签名不正确直接返回 ");
                ////    return; 
                ////}
                //////其次验证是否在有效期内（也应该必须） 
                ////var now = ToUnixEpochDate(DateTime.UtcNow);
                ////success = success && (now >= long.Parse(payLoad["nbf"].ToString()) && now < long.Parse(payLoad["exp"].ToString()));

                //////再其次 进行自定义的验证 
                ////success = success && validatePayLoad(payLoad, setting);

                ////return success;

                ////if (header.ContainsKey("Authorization"))
                ////{
                ////    var auth = header["Authorization"];
                ////    Console.WriteLine(auth);
                ////}
                ////else
                ////{
                ////    ResponseError(context, "必须包含Authorization权限");
                ////    return;
                ////}
                ////var requestContent = requestReader.ReadToEnd();
                //context.Request.Body.Position = 0;
                //Console.WriteLine("Url:" + url);
                ////context.Request.Path.Value.ToString()
                //string path = context.Request.Path.Value;


                ////测试权限
                //if (url.ToLower().Contains("members/helloword"))
                //{
                //    ResponseError(context, "测试无权限");
                //    return;
                //}
                await _next(context);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            await Task.CompletedTask;
        }

        //private async void ResponseError(HttpContext context, string errormsg)
        //{
        //    CommonResponse novalue_response = new CommonResponse();
        //    novalue_response.Status = 501;
        //    novalue_response.Code = 501;
        //    novalue_response.Message = errormsg;
        //    var jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(novalue_response);
        //    context.Response.ContentType = "application/json";
        //    context.Response.StatusCode = 501;
        //    await context.Response.BodyWriter.WriteAsync(jsonUtf8Bytes);
        //    await context.Response.BodyWriter.FlushAsync();
        //    await context.Response.CompleteAsync();
        //}
    }
}
